package com.singzi.appo.service_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.singzi.appo.service_user.mapper.UserInfoMapper;
import com.singzi.appo.service_user.service.UserInfoService;
import com.singzi.hospappo.common.exception.AppoException;
import com.singzi.hospappo.common.helper.JwtHelper;
import com.singzi.hospappo.common.result.ResultCodeEnum;
import com.singzi.hospappo.model.user.UserInfo;
import com.singzi.hospappo.vo.user.LoginVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从login获取输入的手机号，和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new AppoException(ResultCodeEnum.PARAM_ERROR);
        }

        //TODO 判断手机验证码和输入的验证码是否一致


        //判断是否是第一次登录
        QueryWrapper<UserInfo> userWrapper = new QueryWrapper<>();
        userWrapper.eq("phone", phone);
        //第一次登录
        UserInfo userInfo = baseMapper.selectOne(userWrapper);
        if(userInfo == null){
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }
        if(userInfo.getStatus() == 0) {

            throw new AppoException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //不是第一次，直接登录
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)){
             name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("name", name);
        map.put("token", token);
        return map;
    }
}
